const obj = {
    name: "echo",
    age: 18
};
let activeFn = null;
class Depend {
    constructor() {
        this.arrFn = new Set();
    }
    depend() {
        if (activeFn)
            this.arrFn.add(activeFn);
    }
    notify() {
        this.arrFn.forEach(fn => fn());
    }
}


const depend = new Depend();
const weakmap = new WeakMap();

function getTarget(obj, key) {
    let map = weakmap.get(obj);
    if (!map) {
        map = new Map();
        weakmap.set(obj, map);
    }
    let depend = map.get(key);
    if (!depend) {
        depend = new Depend();
        map.set(key, depend);
    }
    return depend;
}
for (const key of Object.keys(obj)) {
    let value = obj[key];
    Object.defineProperty(obj, key, {
        get: function () {
            const depend = getTarget(obj, key);
            depend.depend();
            return value;
        },
        set: function (newValue) {
            const depend = getTarget(obj, key);
            value = newValue;
            depend.notify();
        }
    });
}



function watchFn(fn) {
    activeFn = fn;
    fn();
    activeFn = null;
}

function foo() {
    console.log("这里是foo函数");
    console.log(obj.name);
}
watchFn(foo);
watchFn(() => {
    console.log("这里是bar函数");
    console.log(obj.age);
});
obj.age = 12;
obj.name = "er";